<template>
  <div class="no-scroll-div" style="margin: 0 auto; height: 100%">

    <el-row class="tools">
      <!--      文件上传-->
      <el-col :span="4">
        <!-- 上传按钮  -->
        <el-button type="primary" style="margin-left: 16px" @click="drawer = true">
          上传文件
        </el-button>

        <!-- 上传抽屉  -->
        <el-drawer v-model="drawer" title="I am the title" :with-header="false">
          <!--          <UploadFile/>-->
          <div>

            <!--            <el-button class="button-container" type="success" @click="uploadFiles() ;">提 交</el-button>-->

            <el-upload
                ref="uploadFileRef"
                class="avatar-uploader"
                :action="'http://localhost:6301/file'"
                :file-list="fileList"
                :auto-upload="true"
                :show-file-list="true"
                multiple
                drag
                :before-upload="beforeUpload"
                :limit="5"
                :on-exceed="handleExceed"
                :on-success="handleUploadSuccess"
                :on-error="handleUploadError"
            >
              <el-icon class="el-icon--upload">
                <upload-filled/>
              </el-icon>
              <div class="el-upload__text">
                Drop file here or <em>click to upload</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  上传规则：
                </div>
                <div class="el-upload__tip">
                  1、最多选择5张 jpg/png/jpeg 格式文件
                </div>
                <div class="el-upload__tip">
                  2、文件格式必须为:【xxx.文件类型】
                </div>
<!--                <div class="el-upload__tip">-->
<!--                  3、文件名只能有一个点号-->
<!--                </div>-->
                <div class="el-upload__tip">
                  3、单张文件限制小于 4 M
                </div>
              </template>
            </el-upload>


          </div>
        </el-drawer>
      </el-col>

      <!-- 下拉框 -->
      <el-col :span="6">
        <el-select placeholder="选择查询条件" v-model="selectedCondition" clearable>
          <el-option v-for="item in options"
                     :key="item.value"
                     :label="item.label"
                     :value="item.value"
          />
        </el-select>
      </el-col>
      <!-- 输入框 -->
      <el-col :span="10">
        <el-input
            v-model="input"
            placeholder="请输入搜索内容"
            @keyup.enter="search"
            clearable
        />
      </el-col>
      <!-- 搜索按钮 -->
      <el-col :span="4">
        <el-button type="primary" :icon="Search" @click="search">
          搜索
        </el-button>
      </el-col>

    </el-row>

    <!--    文件列表-->
    <el-table :data="fileListToShow" highlight-current-row show-header stripe height="534px"
              style=" margin-top: 50px;">
      <el-table-column prop="name" label="图片名"/>
      <el-table-column prop="size" label="大小">
        <template v-slot="scope">
          <div v-if="scope.row.size / 1024 > 1">{{ Math.round(scope.row.size / 1024 * 10) / 10 }} KB</div>
          <div v-else-if="scope.row.size / 1024 < 1">{{ Math.round(scope.row.size * 10) / 10 }} B</div>
        </template>
      </el-table-column>
      <el-table-column prop="update_stamp" label="修改时间">
        <template v-slot="scope">
          <div>{{ moment(scope.row.update_stamp * 1000).format('YYYY-MM-DD HH:mm:ss') }}</div>
        </template>
      </el-table-column>

      <el-table-column label="预览">
        <template v-slot="scope">
          <el-image style="width: 110px; height: 100px" :src="scope.row.url"/>

        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot="scope">
          <a :href="scope.row.url">下载</a>
          <FileEdit @search="search" :uuid="scope.row.uuid" :name="scope.row.name"/>
          <a href="javascript:void(0)" @click="deleteFile(scope.row.uuid, scope.row.name)">删除</a>
        </template>
      </el-table-column>

    </el-table>

    <!--    分页组件-->
    <el-pagination
        size="small"
        background
        layout="prev, pager, next"
        class="mt-4"
        v-model:page-size="searchData.limit"
        v-model:current-page="searchData.current"
        :total="total"
        @current-change="page"
    />
  </div>


</template>

<script setup>
import {doDelete, doGet} from '@/http/httpRequest.js';
import {onMounted, reactive, ref} from "vue";
import moment from 'moment';
import {ElMessage, ElMessageBox} from "element-plus";
import FileEdit from "@/views/FileEdit.vue";
import {Search, UploadFilled} from "@element-plus/icons-vue";
import {validateFileName} from "@/tool/pattern.js"

// 定义文件展示模型
const file = {
  "uuid": "",
  "name": "",
  "url": "",
  "size": 0,
  "update_stamp": ""
}

// ==== 分页列表 ====
const fileListToShow = ref([file]) // 全部分页数据
const total = ref(0)
const searchData = reactive({
  current: 1,
  limit: 4
})

// ==== 搜索框 ====
const selectedCondition = ref('name')
const input = ref('')
const options = [
  {
    value: 'name', label: '图片名+图片类型',
  },
  {
    value: 'type', label: '图片类型',
  },

]

// ==== 刷新 ====
const drawer = ref(false)

// 页面加载,初始化数据
onMounted(() => {
  init()
})


const params = {
  current: 1,
  size: 4,
  condition: null,
  query: null
}

// 页面挂载时请求数据
function init() {
  params.current = 1
  params.size = 4
  searchData.current = 1
  searchData.limit = 4
  getData(params)
}

// 新增操作 导致的页面刷新时请求数据
function reload() {
  params.current = 1
  params.size = 4
  searchData.current = 1
  searchData.limit = 4
  params.query = ''
  input.value = ''
  getData(params)
}

// 条件查询时请求数据，以及删除、修改操作之后依然按照条件显示
function search() {
  if (!selectedCondition.value) {
    // warning('请选择查询条件')
    selectedCondition.value = "name"
  }
  params.condition = selectedCondition.value
  params.query = input.value.trim()
  params.current = 1
  params.size = 4
  searchData.current = 1
  searchData.limit = 4
  console.log(params)

  getData(params)
}

// 切换分页时请求数据
function page() {
  params.condition = selectedCondition.value
  params.query = input.value.trim()
  params.current = searchData.current
  params.size = searchData.limit

  getData(params)
}

// 发送网络请求，作为 init、reload、search、page 的底层方法
function getData(params) {
  doGet("/file", params).then((resp) => {
    fileListToShow.value = resp.data.data.files
    total.value = resp.data.data.total
  })
}

// 删除文件
function deleteFile(uuid, name) {
  ElMessageBox.confirm(
      '文件【' + name + '】将会被删除，请确认！',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        doDelete("/file", {
          params: {
            "uuid": uuid,
            "name": name
          }
        }).then((response) => {
          search()
          if (response.data.code === 200) {
            ElMessage({
              type: 'success',
              message: "文件删除成功:【" + response.data.data + "】",
            })
          } else {
            message("info", "文件删除失败:【" + response.data.message + "】")
          }
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消操作',
        })
      })
}

// 消息提示
function message(type, msg) {
  ElMessage({
    type: type,
    message: msg,
  })
}


// ========   文件上传 api ========
let fileList = ref([])
const uploadFileRef = ref([])

// 文件上传之前执行
const beforeUpload = (file) => {
  // 限制文件大小 < 4MB
  const maxSize = 4 * 1024 * 1024;
  if (file.size > maxSize) {
    message("info", "文件过大")
    return false;
  }
  if (! validateFileName(file.name)) {
    console.log("上传 不合法")
    message("info",  `文件名【 ${file.name}】 不合法`)
    return false;
  }

  return true;
};

// 超出文件上限时提示
const handleExceed = (files) => {
  message("info", "超出上传数量限制")
  return false
};

// 处理上传成功的回调函数
const handleUploadSuccess = (response) => {
  console.log("success")
  if (response.code === 200) {
    // message("success", "上传文件成功:【" + response.data + "】")
    // 不提示文件名，防止在多文件提交时，只显示一个的 bug
    message("success", "上传文件成功")
  } else {
    message("info", "上传文件失败:【" + response.data + "】")
  }
  reload()
  fileList.value = []

};

// 处理上传失败的回调函数
const handleUploadError = (error, file) => {
  message("info", "上传文件失败")
};


</script>

<style scoped>
.button-container {
  margin: 20px 43%;
}

/* el-main 区域不滚动 */
.no-scroll-div {
  overflow: hidden;
}

.tools {
  margin-top: 32px;
}

.el-pagination {
  text-align: center;
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

.text {
  text-align: center;
  justify-content: center;
}

</style>
